package com.quartz.service;

import com.quartz.entity.ScheduleJobEntity;
import com.quartz.entity.ScheduleJobLogEntity;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.util.Date;


/**
 * 定时任务
 *
 * @author Mark lin5178@126.com
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class ScheduleJob extends QuartzJobBean {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
    protected void executeInternal(JobExecutionContext context) {
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap()
        		.get(ScheduleJobEntity.JOB_PARAM_KEY);
        //数据库保存执行记录
        ScheduleJobLogEntity log = new ScheduleJobLogEntity();
        log.setJobId(scheduleJob.getJobId());
        log.setMethod(scheduleJob.getMethod());
        log.setParams(scheduleJob.getParams());
        log.setCreateTime(new Date());
        //任务开始时间
        long startTime = System.currentTimeMillis();
        try {
            //执行任务
        	logger.info("任务准备执行，任务ID：" + scheduleJob.getJobId());

//			Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
			//根据class获取实例信息
			Class<?> jobClass = scheduleJob.getJobClass();
			Object target = jobClass.getDeclaredConstructor().newInstance();
			//调用事例中run方法
			if(scheduleJob.getMethodType() == 1){
				if(StringUtils.isBlank(scheduleJob.getParams())){
					scheduleJob.setParams("");
				}
				Method method = target.getClass().getDeclaredMethod(scheduleJob.getMethod(), String.class);
				method.invoke(target, scheduleJob.getParams());
			}else{
				Method method = target.getClass().getDeclaredMethod(scheduleJob.getMethod());
				method.invoke(target);
			}
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setTimes(times);
			//任务状态    0：成功    1：失败
			log.setStatus(0);

			logger.info("任务执行完毕，任务ID：" + scheduleJob.getJobId() + "  总共耗时：" + times + "毫秒");
			callback(scheduleJob,log);
		} catch (Exception e) {
			logger.info("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setTimes(times);
			//任务状态    0：成功    1：失败
			log.setStatus(1);
			log.setError(StringUtils.substring(e.toString(), 0, 2000));
			callback(scheduleJob,log);
		}
    }

	public void callback(ScheduleJobEntity scheduleJob,ScheduleJobLogEntity log){
		try{
			Class<?> jobClass = scheduleJob.getJobClass();
			Object target = jobClass.getDeclaredConstructor().newInstance();
			Method method = target.getClass().getDeclaredMethod("callBack", ScheduleJobLogEntity.class);
			method.invoke(target, log);
		}catch (Exception ec){
			ec.printStackTrace();
		}
	}

}
